<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="分类状态">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 240px">
          <el-option label="正常" value="1" />
          <el-option label="禁用" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增一级分类</el-button>
      </el-col>
    </el-row>

    <!-- 分类列表 -->
    <el-table
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      style="width: 100%"
    >
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="parent_id" label="父分类ID" width="100" />
      <el-table-column prop="level" label="分类级别" width="100" />
      <el-table-column prop="priority" label="优先级" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.status === 1 ? '正常' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180" />
      <el-table-column prop="update_time" label="更新时间" width="180" />
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">添加下级分类</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleDisable(scope.row)">禁用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑分类弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="400px">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="所属上级分类" prop="parentName">
          <el-input v-model="form.parentName" readonly placeholder="请选择上级分类" />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" maxlength="15" />
        </el-form-item>
        <el-form-item label="分类级别" prop="level">
          <el-input v-model="form.level" placeholder="请输入分类级别" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择" clearable>
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-ui';
import * as categoryApi from '@/api/course/category'; // 引入API方法

export default {
  name: 'CategoryManagement',
  data() {
    return {
      loading: false,
      showSearch: true,
      categoryList: [],
      queryParams: {
        status: undefined,
        name: undefined
      },
      form: {
        id: undefined,
        parent_id: undefined,
        parentName: '',
        name: '',
        level: 1,
        priority: 1,
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 15, message: '分类名称长度不超过15个字符', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请输入分类级别', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请输入优先级', trigger: 'blur' }
        ]
      },
      open: false,
      title: '',
      isExpandAll: true,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      categoryApi.listCategory(this.queryParams).then(response => {
        this.loading = false;
        const data = response.data;
        if (data && Array.isArray(data.rows) && data.rows.length > 0) {
          this.categoryList = data.rows;
        } else {
          // 处理空数据或无效数据的情况
          this.categoryList = [];
          ElMessage.warning('没有查询到任何数据');
        }
      }).catch(error => {
        this.loading = false;
        let errorMessage = '获取分类列表失败: 未知错误';
        if (error && error.response && error.response.data) {
          errorMessage = '获取分类列表失败: ' + (error.response.data.message || '无具体错误信息');
          console.error('获取分类列表失败:', error.response.data);
        } else if (error) {
          console.error('请求失败:', error);
          errorMessage = '请求失败: ' + (error.message || '无具体错误信息');
        } else {
          console.error('未知错误');
        }
        ElMessage.error(errorMessage);
      });
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        status: undefined,
        name: undefined
      };
      this.getList();
    },
    handleAdd(parentNode) {
      this.title = parentNode ? '添加下级分类' : '新增一级分类';
      this.form = {
        id: undefined,
        parent_id: parentNode ? parentNode.id : 0,
        parentName: parentNode ? parentNode.name : '',
        name: '',
        level: parentNode ? (parentNode.level + 1) : 1,
        priority: 1,
        status: 1
      };
      this.open = true;
    },
    handleUpdate(row) {
      this.title = '编辑分类';
      this.form = { ...row, parentName: row.parent_id ? this.getParentName(row.parent_id) : '' };
      this.open = true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const apiCall = this.form.id ? categoryApi.updateCategory : categoryApi.addCategory;
          apiCall(this.form).then(response => {
            this.open = false;
            this.getList();
            ElMessage.success(this.form.id ? '更新分类成功' : '新增分类成功');
          }).catch(error => {
            this.loading = false;
            if (error && error.response) {
              ElMessage.error(this.form.id ? '更新分类失败: ' + error.response.data.message : '新增分类失败: ' + error.response.data.message);
              console.error('分类操作失败:', error.response.data);
            } else {
              ElMessage.error(this.form.id ? '更新分类失败: 未知错误' : '新增分类失败: 未知错误');
              console.error('分类操作失败: 未知错误');
            }
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm('确定要删除此分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        categoryApi.deleteCategory(row.id).then(response => {
          this.getList();
          ElMessage.success('删除分类成功');
        }).catch(error => {
          if (error && error.response) {
            ElMessage.error('删除分类失败: ' + error.response.data.message);
            console.error('删除分类失败:', error.response.data);
          } else {
            ElMessage.error('删除分类失败: 未知错误');
            console.error('删除分类失败: 未知错误');
          }
        });
      }).catch(() => {
        ElMessage.info('取消删除');
      });
    },
    handleDisable(row) {
      const newStatus = row.status === 1 ? 2 : 1; // 切换状态
      const action = newStatus === 1 ? '启用' : '禁用';
      this.$confirm(`确定要${action}此分类吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        categoryApi.disableCategory(row.id, newStatus).then(response => {
          this.getList();
          ElMessage.success(`${action}分类成功`);
        }).catch(error => {
          if (error && error.response) {
            ElMessage.error(`${action}分类失败: ${error.response.data.message}`);
            console.error(`${action}分类失败:`, error.response.data);
          } else {
            ElMessage.error(`${action}分类失败: 未知错误`);
            console.error(`${action}分类失败: 未知错误`);
          }
        });
      }).catch(() => {
        ElMessage.info('取消操作');
      });
    },
    getParentName(parentId) {
      const parent = this.categoryList.find(item => item.id === parentId);
      return parent ? parent.name : '未知分类';
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
